<!DOCTYPE html>
<html class="no-js" lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title th:text="|Search Results for '${keyword}' - Shoplook|">Search Results - Shoplook</title>
    <meta name="description" content="description">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Favicon -->
    <link rel="shortcut icon" th:href="@{/assets/images/favicon.png}"/>
    <!-- Plugins CSS -->
    <link rel="stylesheet" th:href="@{/assets/css/plugins.css}">
    <!-- Main Style CSS -->
    <link rel="stylesheet" th:href="@{/assets/css/style.css}">
    <link rel="stylesheet" th:href="@{/assets/css/responsive.css}">
    <style>
        .search-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px 0;
        }
        .search-stats {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .filter-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .hot-keywords {
            margin-top: 15px;
        }
        .keyword-tag {
            display: inline-block;
            background: #e9ecef;
            padding: 4px 12px;
            margin: 2px;
            border-radius: 15px;
            font-size: 0.85rem;
            text-decoration: none;
            color: #495057;
            transition: all 0.2s;
        }
        .keyword-tag:hover {
            background: #007bff;
            color: white;
            text-decoration: none;
        }
        .product-grid-item {
            margin-bottom: 30px;
        }
        .sort-options {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body class="search-page">
<!--Pre-Loader-->
<div id="pre-loader" class="preloader">
    <div class="preloader-in h2">
        <span>S</span><span>H</span><span>O</span><span>P</span><span>L</span><span>O</span><span>O</span><span>K</span>
    </div>
</div>
<!--End Pre-Loader-->
<div class="page-wrapper">
    <!--引入片段-->
    <div th:replace="~{include_header::header}"></div>

    <div id="page-content">
        <!--Search Header-->
        <div class="search-header">
            <div class="container">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h1 class="mb-2" th:if="${keyword}" th:text="|Search Results for '${keyword}'|">Search Results</h1>
                        <h1 class="mb-2" th:unless="${keyword}">Browse All Products</h1>
                        <p class="mb-0" th:text="|Found ${total ?: 0} products|">Found 0 products</p>
                    </div>
                    <div class="col-md-4 text-end">
                        <!-- 搜索框 -->
                        <div class="search-form">
                            <form th:action="@{/search}" method="get" class="d-flex">
                                <input type="text" name="q" class="form-control me-2" 
                                       th:value="${keyword}" placeholder="Search products...">
                                <button type="submit" class="btn btn-light">
                                    <i class="an an-search"></i>
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 搜索统计和筛选 -->
        <div class="container">
            <div class="search-stats">
                <div class="row align-items-center">
                    <div class="col-md-6">
                        <p class="mb-0">
                            <strong th:text="${total ?: 0}">0</strong> products found
                            <span th:if="${keyword}" th:text="|for '${keyword}'|"></span>
                        </p>
                    </div>
                    <div class="col-md-6 text-end">
                        <!-- 排序选项 -->
                        <div class="sort-options">
                            <label>Sort by:</label>
                            <select class="form-select" style="width: auto;" onchange="sortProducts(this.value)">
                                <option value="relevance" th:selected="${sortBy == 'relevance'}">Relevance</option>
                                <option value="price_low" th:selected="${sortBy == 'price_low'}">Price: Low to High</option>
                                <option value="price_high" th:selected="${sortBy == 'price_high'}">Price: High to Low</option>
                                <option value="newest" th:selected="${sortBy == 'newest'}">Newest First</option>
                                <option value="popularity" th:selected="${sortBy == 'popularity'}">Most Popular</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <!-- 侧边栏筛选 -->
                <div class="col-12 col-sm-12 col-md-3 col-lg-3 sidebar filterbar">
                    <div class="filter-section">
                        <h5>Search History</h5>
                        <div th:if="${searchHistory != null and !searchHistory.isEmpty()}">
                            <div th:each="history : ${searchHistory}">
                                <a th:href="@{/search(q=${history})}" class="keyword-tag" th:text="${history}">History</a>
                            </div>
                            <div class="mt-2">
                                <button class="btn btn-sm btn-outline-secondary" onclick="clearSearchHistory()">
                                    <i class="an an-times"></i> Clear History
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="filter-section">
                        <h5>Hot Keywords</h5>
                        <div class="hot-keywords" th:if="${hotKeywords != null and !hotKeywords.isEmpty()}">
                            <div th:each="keyword : ${hotKeywords}">
                                <a th:href="@{/search(q=${keyword})}" class="keyword-tag" th:text="${keyword}">Hot Keyword</a>
                            </div>
                        </div>
                    </div>

                    <!-- 分类筛选 -->
                    <div class="filter-section" th:if="${categories != null and !categories.isEmpty()}">
                        <h5>Categories</h5>
                        <ul class="list-unstyled">
                            <li th:each="category : ${categories}">
                                <a th:href="@{/search(q=${keyword}, categoryId=${category.id})}" 
                                   class="d-block py-1 text-decoration-none"
                                   th:classappend="${categoryId == category.id} ? 'text-primary fw-bold' : 'text-muted'"
                                   th:text="${category.name}">Category Name</a>
                            </li>
                        </ul>
                    </div>

                    <!-- 价格筛选 -->
                    <div class="filter-section">
                        <h5>Price Range</h5>
                        <form th:action="@{/search}" method="get" class="price-filter-form">
                            <input type="hidden" name="q" th:value="${keyword}">
                            <input type="hidden" name="categoryId" th:value="${categoryId}">
                            <div class="row g-2">
                                <div class="col-6">
                                    <input type="number" class="form-control form-control-sm" name="minPrice" 
                                           placeholder="Min" th:value="${minPrice}">
                                </div>
                                <div class="col-6">
                                    <input type="number" class="form-control form-control-sm" name="maxPrice" 
                                           placeholder="Max" th:value="${maxPrice}">
                                </div>
                                <div class="col-12">
                                    <button type="submit" class="btn btn-sm btn-primary w-100">Apply</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- 商品结果列表 -->
                <div class="col-12 col-sm-12 col-md-9 col-lg-9">
                    <!-- 商品网格 -->
                    <div th:if="${products != null and !products.isEmpty()}">
                        <div class="row">
                            <div class="col-6 col-sm-6 col-md-4 col-lg-4 product-grid-item" th:each="product : ${products}">
                                <div class="item">
                                    <div class="product-img">
                                        <a th:href="@{/detail(id=${product.id})}" class="product-img">
                                            <img class="primary blur-up lazyload" 
                                                 th:src="${product.mainPicUrl ?: '/assets/images/product-images/default.jpg'}" 
                                                 th:alt="${product.name}" title="">
                                            <img class="hover blur-up lazyload" 
                                                 th:src="${product.mainPicUrl ?: '/assets/images/product-images/default.jpg'}" 
                                                 th:alt="${product.name}" title="">
                                        </a>
                                        <!-- 商品标签 -->
                                        <div class="product-labels" th:if="${product.isHot == 1}">
                                            <span class="lbl pr-label1">Hot</span>
                                        </div>
                                        <!-- 快速操作按钮 -->
                                        <div class="product-buttons">
                                            <a href="#" class="btn" th:onclick="|addToCart(${product.id})|" title="Add to Cart">
                                                <i class="icon an an-cart" aria-hidden="true"></i>
                                            </a>
                                            <a href="#" class="btn" th:onclick="|toggleFavorite(${product.id})|" title="Add to Wishlist">
                                                <i class="icon an an-heart" aria-hidden="true"></i>
                                            </a>
                                        </div>
                                    </div>
                                    <div class="product-details text-left">
                                        <div class="brand-name">Brand</div>
                                        <div class="product-name">
                                            <a th:href="@{/detail(id=${product.id})}" th:text="${product.name}">Product Name</a>
                                        </div>
                                        <div class="product-price">
                                            <span class="old-price" th:if="${product.marketPrice}" 
                                                  th:text="|¥${product.marketPrice}|">¥999.00</span>
                                            <span class="price" th:text="|¥${product.price}|">¥499.00</span>
                                        </div>
                                        <div class="product-stock" th:if="${product.stock}">
                                            <small class="text-muted" th:text="|${product.stock} in stock|">10 in stock</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 分页 -->
                        <div class="pagination-section mt-4" th:if="${totalPages > 1}">
                            <nav aria-label="Search results pagination">
                                <ul class="pagination justify-content-center">
                                    <li class="page-item" th:classappend="${currentPage <= 1} ? 'disabled'">
                                        <a class="page-link" th:href="@{/search(q=${keyword}, categoryId=${categoryId}, page=${currentPage - 1})}">Previous</a>
                                    </li>
                                    <li class="page-item" th:each="pageNum : ${#numbers.sequence(1, totalPages)}"
                                        th:classappend="${pageNum == currentPage} ? 'active'">
                                        <a class="page-link" th:href="@{/search(q=${keyword}, categoryId=${categoryId}, page=${pageNum})}" 
                                           th:text="${pageNum}">1</a>
                                    </li>
                                    <li class="page-item" th:classappend="${currentPage >= totalPages} ? 'disabled'">
                                        <a class="page-link" th:href="@{/search(q=${keyword}, categoryId=${categoryId}, page=${currentPage + 1})}">Next</a>
                                    </li>
                                </ul>
                            </nav>
                        </div>
                    </div>

                    <!-- 搜索无结果 -->
                    <div th:if="${products == null or products.isEmpty()}" class="text-center py-5">
                        <i class="an an-search" style="font-size: 4rem; color: #ddd;"></i>
                        <h4 class="mt-3">No Products Found</h4>
                        <p class="text-muted" th:if="${keyword}" th:text="|Sorry, we couldn't find any products matching '${keyword}'|">
                            Sorry, we couldn't find any products matching your search.
                        </p>
                        <p class="text-muted" th:unless="${keyword}">Try browsing our categories or use the search box above.</p>
                        
                        <div class="mt-4">
                            <h6>Suggestions:</h6>
                            <ul class="list-unstyled">
                                <li>• Check your spelling</li>
                                <li>• Try more general keywords</li>
                                <li>• Browse our categories</li>
                            </ul>
                        </div>
                        
                        <div class="mt-4">
                            <h6>Popular Searches:</h6>
                            <div th:if="${hotKeywords != null and !hotKeywords.isEmpty()}">
                                <div th:each="hotKeyword : ${hotKeywords}">
                                    <a th:href="@{/search(q=${hotKeyword})}" class="keyword-tag" th:text="${hotKeyword}">Keyword</a>
                                </div>
                            </div>
                        </div>
                        
                        <a th:href="@{/goods}" class="btn btn-primary mt-3">Browse All Products</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Footer -->
<div th:replace="~{include_header::footer}"></div>

<script th:src="@{/assets/js/vendor/jquery-3.6.0.min.js}"></script>
<script th:src="@{/assets/js/vendor/modernizr-3.6.0.min.js}"></script>
<script th:src="@{/assets/js/vendor/bootstrap.min.js}"></script>
<script th:src="@{/assets/js/plugins.js}"></script>
<script th:src="@{/assets/js/main.js}"></script>

<script>
// 排序商品
function sortProducts(sortBy) {
    const url = new URL(window.location);
    url.searchParams.set('sortBy', sortBy);
    url.searchParams.set('page', '1'); // 重置到第一页
    window.location.href = url.toString();
}

// 添加到购物车
function addToCart(productId) {
    $.post('/cart/add', {
        goodId: productId,
        qty: 1
    }).done(function(response) {
        if (response.success) {
            alert('Added to cart successfully!');
        } else {
            alert(response.message || 'Failed to add to cart');
        }
    }).fail(function() {
        alert('Network error, please try again');
    });
}

// 切换收藏状态
function toggleFavorite(productId) {
    // 这里需要先检查当前收藏状态，然后决定是添加还是移除
    $.post('/favorite/add', {
        productId: productId
    }).done(function(response) {
        if (response.success) {
            alert('Added to favorites!');
        } else if (response.message && response.message.includes('已收藏')) {
            // 如果已经收藏，则移除收藏
            $.post('/favorite/remove', {
                productId: productId
            }).done(function(response) {
                if (response.success) {
                    alert('Removed from favorites!');
                }
            });
        } else {
            alert(response.message || 'Operation failed');
        }
    }).fail(function() {
        alert('Network error, please try again');
    });
}

// 清除搜索历史
function clearSearchHistory() {
    if (confirm('Are you sure you want to clear your search history?')) {
        $.post('/search/clear-history').done(function(response) {
            if (response.success) {
                location.reload();
            } else {
                alert(response.message || 'Failed to clear search history');
            }
        }).fail(function() {
            alert('Network error, please try again');
        });
    }
}

// 搜索建议功能
$(document).ready(function() {
    const searchInput = $('input[name="q"]');
    let searchTimeout;
    
    searchInput.on('input', function() {
        const keyword = $(this).val().trim();
        
        clearTimeout(searchTimeout);
        
        if (keyword.length >= 2) {
            searchTimeout = setTimeout(function() {
                $.get('/search/suggest', { q: keyword })
                    .done(function(response) {
                        if (response.success && response.data.length > 0) {
                            showSearchSuggestions(response.data);
                        }
                    });
            }, 300);
        }
    });
});

// 显示搜索建议
function showSearchSuggestions(suggestions) {
    // 这里可以实现搜索建议下拉框
    console.log('Search suggestions:', suggestions);
}
</script>

</body>
</html> 